package cm.cool.system.qiniu;

import java.io.File;
import java.util.UUID;

import com.github.pagehelper.StringUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiniuUpload {
		
    public static final String QINIU_DOMAIN = "oi6buyfwl.bkt.clouddn.com";  
    public static final String BUCKET = "ec-back";  
      
  
    public static Auth auth = null;  
  
    static {  
        String access_key = "pb_1o0pcg_2VrhLrcpvxkmQLu8Dfk6wZyS_fVfJg";  
        String secret_key = "9Ii2z80iq5Bu5UmfVaOaDpoAXBrqw1Hmb9f6tNjd";  
        auth = Auth.create(access_key, secret_key);  
    }  
      
    /** 
     * @param file      待上传的文件 
     * @param destFileName 七牛上显示的文件名 
     * @param bucket 七牛上的存储空间 
     *  
     * @return 七牛上显示的文件名 
     */  
    public static String upload(File file, String destFileName, String bucket) {  
        if (!file.exists()) {  
            return "文件没有找到";  
        }  
        bucket=StringUtil.isEmpty(bucket) ? BUCKET: bucket;  
        String token = auth.uploadToken(bucket);//获取上传凭证token  
        if (StringUtil.isEmpty(token)) {  
        	return "token获取异常";   
        }  
        try {  
            Zone z = Zone.zone2();  
            Configuration c = new Configuration(z);  
            //创建上传对象  
            UploadManager manger = new UploadManager(c);  
            Response res = manger.put(file, destFileName, token);//上传文件并获取回执  
            if (res.isOK()) {  
                Ret ret = res.jsonToObject(Ret.class);  
                System.err.println("----" + ret.key);  
                return ret.key;  
            }  
        } catch (QiniuException e) {  
            e.printStackTrace();  
        }  
        return null;  
    } 
    
    public static void main(String[] args) {
		File file=new File("G:\\xs\\消息.jpg");
		upload(file, UUID.randomUUID().toString(), BUCKET);
	}
}


class Ret {  
    public long fsize;  
    public String key;  
    public String hash;  
    public int width;  
    public int height;  
}  